package com.csinc.generate.core.aop;

import com.csinc.generate.core.base.log.LogManager;
import com.csinc.generate.core.base.log.LogTaskFactory;
import com.csinc.generate.core.base.tips.ErrorTip;
import com.csinc.generate.core.exception.BizExceptionEnum;
import com.csinc.generate.core.exception.CsincException;
import com.csinc.generate.core.utils.support.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 *
 * Create By 郭金宝 on 2018/7/23.<br>
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    {
        log.info("全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）");
    }

    /**
     * 拦截业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(CsincException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorTip notFount(CsincException e) {
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(1, e));
        log.error("业务异常:", e);
        return new ErrorTip(e.getCode(), e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public String notFount(RuntimeException e) {
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(1, e));
        HttpUtils.getRequest().setAttribute("tip", "服务器未知运行时异常");
        log.error("运行时异常:", e);
        return "500.html";
    }

    /**
     * 无权访问该资源
     *
     * @author fengshuonan
     */
    @ExceptionHandler(UndeclaredThrowableException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ErrorTip credentials(UndeclaredThrowableException e) {
        HttpUtils.getRequest().setAttribute("tip", "权限异常");
        log.error("权限异常!", e);
        return new ErrorTip(BizExceptionEnum.NO_PERMITION.getCode(), BizExceptionEnum.NO_PERMITION.getMessage());
    }

    private void assertAjax(HttpServletRequest request, HttpServletResponse response) {
        if (request.getHeader("x-requested-with") != null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            //如果是ajax请求响应头会有，x-requested-with
            response.setHeader("sessionstatus", "timeout");//在响应头设置session状态
        }
    }

//
//    /**
//     * 验证码错误
//     *
//     */
//    @ExceptionHandler(InvalidKaptchaException.class)
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
//    public String credentials(InvalidKaptchaException e, Model model) {
//        String username = HttpUtils.getRequest().getParameter("username");
//        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "验证码错误", HttpUtils.getIp()));
//        model.addAttribute("tips", "验证码错误");
//        return "/login.html";
//    }

}
